import { defineComponent, inject } from 'vue'
import { FormItemContext, form_item_key } from '../form/type';
import './index.scss';
export default defineComponent({
  name: "Input",
  inheritAttrs: false,
  props: {
    modelValue: { type: String, default: '' },
    type: {
      default: 'text',
      validator: (value: string) => {
        return ['text', 'number', 'password', 'tel', 'textarea', 'time'].includes(value);
      }
    }
  },
  emits: ['update:modelValue'],
  
  setup(props, { emit, attrs }) {

    const formItemCtx = inject<FormItemContext>(form_item_key);
    const onInput = (event: Event) => {
      const value = (event.target as HTMLInputElement).value;
      if (value !== props.modelValue) {
        emit('update:modelValue', value);
        formItemCtx?.handlerValueChange(value);
      }
    };

    const onBlur = () => { 
      formItemCtx?.handlerValueBlur(props.modelValue)
    };

    return () => {
      return (
        <div class="ant-field-wrap">
          <input class="ant-field"
            type={props.type}
            autocomplete="new-password"
            placeholder={attrs.placeholder as string}
            onInput={ onInput }
            onBlur={ onBlur }
            value={ props.modelValue}
            />
        </div>
      )
    }
  }
})